var template = require('../tabbar/template.js');
var WxSearch = require('../../../templates/wxSearch/wxSearch.js');
const db = wx.cloud.database()
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusType: ["上架销售中","待上架","已下架"],//,"轮播图","今日特价","特别推荐"
    hasRefund: false,
    currentType: 0,//选中的状态
    specialQuery:"",//上架销售中的商品 特殊查询
    tabClass: ["",  ""],
    keyword:"",
    pagenum:1,
    pagesize:20,
    recommendGoodsShow:[],
    loadingMore:false,
    isEnd:false,//是否到底
    stv: {
      windowWidth: 0,
      windowHeight: 0,
    },
    height: [],
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      //切换选中
      currentType: parseInt(options.type)
    });
   
    var that = this;
    try {
      var res = wx.getSystemInfoSync()
      console.log('system information', res)
      if (that.data.noticeList) {
        that.setData({
          stv: {
            windowsWidth: res.windowWidth,
            windowsHeight: res.windowHeight
          },
          height: (750 / res.windowWidth) * res.windowHeight - 100
        })
      } else {
        that.setData({
          stv: {
            windowsWidth: res.windowWidth,
            windowsHeight: res.windowHeight
          },
          height: (750 / res.windowWidth) * res.windowHeight
        })
      }

    } catch (e) {

    }
    console.log('stv', that.data.stv, that.data.height)
  },
  statusTap: function (e) {
    const curType = e.currentTarget.dataset.index;
   
    this.setData({
      currentType: parseInt(curType),
      recommendGoodsShow:[],
      keyword:"",
      isEnd:false
    });
   
    this.onShow();
  },
  
 
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    wx.hideHomeButton()//隐藏主页图标
    this.setData({
       recommendGoodsShow:[],
       isEnd:false,
       pagenum:1
     })
    that.getRGshow()
  },
  toDetailsTap: function (e) {
    wx.navigateTo({
      url: "/pages/goods-details/index?id=" + e.currentTarget.dataset.id
    })
  },
   //去修改
   updateShop(e){
    wx.navigateTo({
      url: '../addgoods/update_goods?id='+e.currentTarget.dataset.id,
    })
   },
   //下架 停止销售
   stopSelling(e){
    var that = this;
    wx.showModal({
      title: '确定下架该商品吗？',
      content: '',
      success: function (res) {
        if (res.confirm) {
          const db = wx.cloud.database()
        
          db.collection('goods').doc(e.currentTarget.dataset.id).update({
            data: {
              status:0,//0
             
            },
            success: function(res) {
              console.log(res)
              //清空列表
              that.setData({
                  recommendGoodsShow:[],
                  isEnd:false,
                  pagenum:1
                })
              that.getRGshow();

            }
          })
         
          
        }
      }
    })
   },
 
  getRGshow(){
    console.log("加载下页")
    var that = this;
    //isEnd是否已经最后一页
    if (that.data.isEnd) {
      console.log('isEnd, return...')
      return;
    }
    console.log('notEnd, continue')
    that.setData({
      loadingMore: true
    })
    var where ={}
    let commandtype={}
    if(that.data.keyword){
      where =  {	 	//搜索框查询
        name:{							
          $regex:'.*' + that.data.keyword + '.*',	
          $options: 'i'						
        }
      }
    }
    else if(that.data.currentType==0){
      where = {status:1}
      if(that.data.specialQuery==1){
        where = {status:1,banner:1}
      } else  if(that.data.specialQuery==2){
        where = {tejia:1,status:1}
      }else  if(that.data.specialQuery==3){
        where = {recommendStatus:1,status:1}
      }else  if(that.data.specialQuery==4){
        where = {stores:0,status:1}
      }else  if(that.data.specialQuery==5){
        where = {status:1}
        commandtype=[{
          type:'lt',
          ziduan:'stores',
          value:20
        }]
    }
    }else  if(that.data.currentType==1){
      where = {status:2} //待上架
      
    }else if(that.data.currentType==2){
        where = {status:0}
        
    }
    
  
    console.log(that.data.pagenum)
    var skip = that.data.pagesize*(that.data.pagenum -1)
    console.log(skip)

    var recommendGoodsShow = that.data.recommendGoodsShow;
    var rgShowLen = recommendGoodsShow.length;
    console.log('rgShowLen', rgShowLen)
    
    wx.cloud.callFunction({
      // 云函数名称
      name: 'crud',
      // 传给云函数的参数
      data: {
        db:"goods",
        type:"getpages",
        data:"",
        indexKey:"",
        //待筛选的参数-库存 >0
        skip:skip,
        limit:that.data.pagesize,
        commandtype:commandtype,
        condition:where,
      },
    }) .then(res => {
      that.setData({
        pagenum : that.data.pagenum+1
      })
      console.log(res)
      //如果有数据
      if(res.result){
          let ress = res.result.result.data
          if (ress.length > 0) {
            for (var i = 0; i <ress.length; i++) {
              recommendGoodsShow.push(ress[i])
            }
             this.setData({
               recommendGoodsShow:recommendGoodsShow,
              loadingMore: false,
            
              })
               console.log('[数据库] [查询记录] 成功: ', res) 
          }else{
            console.log("数据为0")
             this.setData({
              
              loadingMore: false,
              isEnd:true
            })
          }
        }else{
           this.setData({
            
            loadingMore: false,
            isEnd:true
            })
        }
    })
    .catch(console.error)
  
      
  },
   //上拉
   onReachBottom: function(){
    console.log("上拉加载分页")
    var that = this
    that.getRGshow()
  },
  wxSearchInput: function (e) {
    var that = this
  // WxSearch.wxSearchInput(e, that);

    that.setData({
      keyword: e.detail.value,
    })
  },
  wxSearchFn: function (e) {
    
    var that = this
    that.setData({
        recommendGoodsShow:[],
        isEnd:false,
        pagenum:1
      })
    that.getRGshow()

  },
  //查询库存<20 的商品
  storesSearchFn_20(){
    var that = this
    
      this.setData({
        currentType: 0,
        specialQuery:5,
        recommendGoodsShow:[],
        keyword:"",
        isEnd:false,
        pagenum:1
      });
    that.getRGshow()
  },
  //查询库存为 0 的商品
  storesSearchFn_0(){
    var that = this
    
      this.setData({
        currentType: 0,
        specialQuery:4,
        recommendGoodsShow:[],
        keyword:"",
        isEnd:false,
        pagenum:1
      });
    that.getRGshow()
  },


  //特价商品
  storesSearchFn_tejia(){
    var that = this
    
    this.setData({
      currentType: 0,
      specialQuery:2,
      recommendGoodsShow:[],
      keyword:"",
      isEnd:false,
      pagenum:1
    });
    that.getRGshow()
  },
  //推荐商品
  storesSearchFn_tuijian(){
    var that = this
    
    this.setData({
      currentType: 0,
      specialQuery:3,
      recommendGoodsShow:[],
      keyword:"",
      isEnd:false,
      pagenum:1
    });
    that.getRGshow()
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this
    that.setData({
      loadingMore: true,
      isEnd: false
    })
    wx.showNavigationBarLoading()
    that.onLoad()
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})